package com.yonyou.cyxdms.sysAuth.service.utill;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;
import java.util.Objects;
import java.util.UUID;

/**
 * <p>Title: AesUtil</p>
 * <p>Description: AES加密解密</p>
 *
 * @author luzizhi
 */
public class AesUtil {
    private static final Logger logger = LoggerFactory.getLogger(AesUtil.class);

    public static void main(String[] args) {
        UUID uuid = UUID.randomUUID();
        String content = "token_" + DateUtils.getYYYYMMdd() + "_" + uuid;
        System.out.println("内容：" + content);
        byte[] encrypt = AesUtil.encrypt(content, PW_SECRET_KEY, 16);//加密
        String parseByte2HexStr = AesUtil.parseByte2HexStr(Objects.requireNonNull(encrypt));//转换为16进制字符串
        System.out.println("加密后：" + parseByte2HexStr);
        byte[] parseHexStr2Byte = AesUtil.parseHexStr2Byte(parseByte2HexStr);
        String decrypt = AesUtil.decrypt(parseHexStr2Byte, PW_SECRET_KEY, 16);
        System.out.println("解密后：" + decrypt);

        System.out.println("UUID：" + uuid);
    }

    /**
     * 加密方式
     */
    private static final String AES_TYPE ="AES/CBC/PKCS5Padding";

    /**
     * 秘钥
     */
    public static final String PW_SECRET_KEY = "EasyRailEveryday";

    /**
     * 初始向量
     */
    private static final String INITIAL_VECTOR = "EasyRailEasyRail";

    /**
     * 加密
     *
     * @param content  需要加密的内容
     * @param password 加密密码
     * @param keySize  密钥长度16,24,32(密码长度为24和32时需要将local_policy.jar/US_export_policy.jar两个jar包放到JRE目录%jre%/lib/security下)
     */
    public static byte[] encrypt(String content, String password, int keySize) {
        try {
            //密钥长度不够用0补齐。
            SecretKeySpec key = new SecretKeySpec(zeroPadding(password.getBytes(Charset.forName("UTF-8")), keySize), "AES");
            //定义加密算法AES 算法模式CBC、补码方式PKCS5Padding
            Cipher cipher = Cipher.getInstance(AES_TYPE);
            //CBC模式模式下初始向量 不足16位用0补齐
            IvParameterSpec iv = new IvParameterSpec(zeroPadding(INITIAL_VECTOR.getBytes(Charset.forName("UTF-8")), 16));
            byte[] byteContent = content.getBytes();
            //初始化加密CBC
            cipher.init(Cipher.ENCRYPT_MODE, key, iv);
            return cipher.doFinal(byteContent);
        } catch (Exception e) {
            logger.error("加密失败",e);
        }
        return null;
    }

    /**
     * 解密
     *
     * @param content  待解密内容
     * @param password 解密密钥
     * @param keySize  密钥长度16,24,32(密码长度为24和32时需要将local_policy.jar/US_export_policy.jar两个jar包放到JRE目录%jre%/lib/security下)
     */
    public static String decrypt(byte[] content, String password, int keySize) {
        try {
            //密钥长度不够用0补齐。
            SecretKeySpec key = new SecretKeySpec(zeroPadding(password.getBytes(), keySize), "AES");
            //定义加密算法AES 算法模式CBC、补码方式PKCS5Padding
          Cipher cipher = Cipher.getInstance(AES_TYPE);
            //CBC模式模式下初始向量 不足16位用0补齐
            IvParameterSpec iv = new IvParameterSpec(zeroPadding(INITIAL_VECTOR.getBytes(Charset.forName("UTF-8")), 16));
            // 初始化解密CBC
            cipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] result = cipher.doFinal(content);
            return new String(result, Charset.forName("UTF-8"));
        } catch (Exception ex) {
           logger.error("解密失败",ex);
        }
        return null;
    }

    /**
     * 将二进制转换成16进制
     */
    public static String parseByte2HexStr(byte[] buf) {
        StringBuilder sb = new StringBuilder();
        for (byte b : buf) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /**
     * 将16进制转换为二进制
     */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) {
            return null;
        }
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

    /**
     * 字符达不到指定长度补0
     */
    private static byte[] zeroPadding(byte[] in, Integer blockSize) {
        Integer copyLen = in.length;
        if (copyLen > blockSize) {
            copyLen = blockSize;
        }
        byte[] out = new byte[blockSize];
        System.arraycopy(in, 0, out, 0, copyLen);
        return out;
    }

}
